var AV = require('leanengine');
var uuid = require('node-uuid');
var config = require('../../cloud/wx/config');
var util = require('../../cloud/wx/util');
var WXPay = require('../../cloud/wx/wxPay');
var common = require('../../cloud/common');
var apis = require('../../cloud/lib/apis');
AV.Cloud.define("getWxPrepayId", function (request, response) {
    if (request.params.orderCode == null || request.params.orderCode == "") {
        return response.success(JSON.stringify(common.getErrArr("请传入正确的参数")));
    } else {
        var orderCode = request.params.orderCode;


        var query = new AV.Query('Live_order');
        query.equalTo("orderCode", parseInt(orderCode));

        query.first({
                success: function (orderObj) {
                    if (orderObj != null) {
                        if (orderObj.get("payStatus") != "0") {
                            return response.success(JSON.stringify(common.getErrArr("订单已关闭或已付款")));
                        } else {
                            var total_fee = parseInt(orderObj.get("cost") * 100);
                            if (orderObj.get("cost") * 100 - parseInt(orderObj.get("cost") * 100) > 0)
                                total_fee += 1;

                            var signParams = {};
                            signParams["appid"] = apis['wxConfig']["APPID"];
                            signParams['mch_id'] = apis['wxConfig']["mch_id"];
                            signParams['partner_key'] = apis['wxConfig']['partner_key2'];
                            signParams['body'] = '直播订单:' + orderObj.get("orderCode");
                            signParams['out_trade_no'] = orderObj.get("orderCode");
                            signParams['total_fee'] = total_fee;
                            signParams['spbill_create_ip'] = '127.0.0.1';
                            signParams['notify_url'] = apis['wxConfig']['notify_url'];
                            signParams['trade_type'] = 'APP';
                            signParams['product_id'] = apis['wxConfig']["mch_id"];
                            signParams['pfx'] = null;//微信商户平台证书
                            var wxpay = WXPay(signParams);
                            wxpay.createUnifiedOrder(signParams, function (err, result) {

                                if (err) {
                                    return response.error(err);
                                } else {

                                    console.log(result);

                                    var returnArr = common.getReturnArr("", "1000", "", result.prepay_id);
                                    return response.success(JSON.stringify(returnArr));
                                }
                            });
                        }
                    } else {
                        //查询要支付的订单
                        var query = new AV.Query('Shop_order');
                        query.equalTo("orderCode", parseInt(orderCode));
                        query.first({
                            success: function (orderObj) {
                                if (orderObj != null) {
                                    if (orderObj.get("status") != apis["order"]["status_noPay"]) {
                                        return response.success(JSON.stringify(common.getErrArr("订单已关闭或已付款")));
                                    } else {
                                        var total_fee = parseInt(orderObj.get("totalPrice") * 100);
                                        if (orderObj.get("totalPrice") * 100 - parseInt(orderObj.get("totalPrice") * 100) > 0)
                                            total_fee += 1;
                                        var signParams = {};
                                        signParams["appid"] = apis['wxConfig']["APPID"];
                                        signParams['mch_id'] = apis['wxConfig']["mch_id"];
                                        signParams['partner_key'] = apis['wxConfig']['partner_key2'];
                                        signParams['body'] = '商品订单:' + orderObj.get("orderCode");
                                        signParams['out_trade_no'] = orderObj.get("orderCode");
                                        signParams['total_fee'] = total_fee;
                                        signParams['spbill_create_ip'] = '127.0.0.1';
                                        signParams['notify_url'] = apis['wxConfig']['notify_url'];
                                        signParams['trade_type'] = 'APP';
                                        signParams['product_id'] = apis['wxConfig']["mch_id"];
                                        signParams['pfx'] = null;//微信商户平台证书
                                        var wxpay = WXPay(signParams);
                                        wxpay.createUnifiedOrder(signParams, function (err, result) {

                                            if (err) {
                                                return response.error(err);
                                            } else {
                                                var returnArr = common.getReturnArr("", "1000", "", result.prepay_id);
                                                return response.success(JSON.stringify(returnArr));
                                            }
                                        });
                                    }
                                } else {
                                    //查询要支付的订单
                                    var query = new AV.Query('Tribe_order');
                                    query.equalTo("orderCode", parseInt(orderCode));
                                    query.first({
                                        success: function (orderObj) {
                                            if (orderObj != null) {
                                                if (orderObj.get("paystatu") != 0) {
                                                    return response.success(JSON.stringify(common.getErrArr("订单已关闭或已付款")));
                                                } else {
                                                    var total_fee = parseInt(orderObj.get("cost") * 100);
                                                    if (orderObj.get("cost") * 100 - parseInt(orderObj.get("cost") * 100) > 0)
                                                        total_fee += 1;
                                                    var signParams = {};
                                                    signParams["appid"] = apis['wxConfig']["APPID"];
                                                    signParams['mch_id'] = apis['wxConfig']["mch_id"];
                                                    signParams['partner_key'] = apis['wxConfig']['partner_key2'];
                                                    signParams['body'] = '部落订单:' + orderObj.get("orderCode");
                                                    signParams['out_trade_no'] = orderObj.get("orderCode");
                                                    signParams['total_fee'] = total_fee;
                                                    signParams['spbill_create_ip'] = '127.0.0.1';
                                                    signParams['notify_url'] = apis['wxConfig']['notify_url'];
                                                    signParams['trade_type'] = 'APP';
                                                    signParams['product_id'] = apis['wxConfig']["mch_id"];
                                                    signParams['pfx'] = null;//微信商户平台证书
                                                    var wxpay = WXPay(signParams);
                                                    wxpay.createUnifiedOrder(signParams, function (err, result) {

                                                        if (err) {
                                                            return response.error(err);
                                                        } else {
                                                            var returnArr = common.getReturnArr("", "1000", "", result.prepay_id);
                                                            return response.success(JSON.stringify(returnArr));
                                                        }
                                                    });
                                                }
                                            } else {
                                                var query = new AV.Query('Shop_order');
                                                query.equalTo("parentOrderCode", (orderCode));
                                                query.find().then(function(orders){
                                                    if(orders && orders.length>0){

                                                        var total_fee = 0;

                                                        for(var i=0;i<orders.length;i++){
                                                            if (orders[i].get("status") != apis["order"]["status_noPay"]) {
                                                                return response.success(JSON.stringify(common.getErrArr("订单已关闭或已付款")));
                                                            }


                                                                total_fee =total_fee+ parseInt(orders[i].get("totalPrice") * 100);
                                                        }

                                                            var signParams = {};
                                                            signParams["appid"] = apis['wxConfig']["APPID"];
                                                            signParams['mch_id'] = apis['wxConfig']["mch_id"];
                                                            signParams['partner_key'] = apis['wxConfig']['partner_key2'];
                                                            signParams['body'] = '商品订单:' + orderCode;
                                                            signParams['out_trade_no'] = orderCode;
                                                            signParams['total_fee'] = total_fee;
                                                            signParams['spbill_create_ip'] = '127.0.0.1';
                                                            signParams['notify_url'] = apis['wxConfig']['notify_url'];
                                                            signParams['trade_type'] = 'APP';
                                                            signParams['product_id'] = apis['wxConfig']["mch_id"];
                                                            signParams['pfx'] = null;//微信商户平台证书
                                                            var wxpay = WXPay(signParams);
                                                            wxpay.createUnifiedOrder(signParams, function (err, result) {

                                                                if (err) {
                                                                    return response.error(err);
                                                                } else {
                                                                    var returnArr = common.getReturnArr("", "1000", "", result.prepay_id);
                                                                    return response.success(JSON.stringify(returnArr));
                                                                }
                                                            });



                                                    }else{
                                                        return response.success(JSON.stringify(common.getErrArr("无效的订单")));

                                                    }
                                                },function(err){

                                                })

                                            }
                                        }
                                    });
                                }
                            }
                        });
                    }

                }, error: function (error) {
                }
            }
        );


    }
})

AV.Cloud.define("getH5WxPrepayId", function (request, response) {
    var total_fee = 1;
    var signParams = {};
    signParams["appid"] = apis['wxConfig']['APPID'];
    signParams['mch_id'] = apis['wxConfig']['mch_id'];
    signParams['partner_key'] = apis['wxConfig']['partner_key'];
    signParams['body'] = '微信浏览器测试支付';
    signParams['out_trade_no'] = new Date().getTime();
    signParams['total_fee'] = total_fee;
    signParams['spbill_create_ip'] = '127.0.0.1';
    signParams['notify_url'] = 'http://tribe.aladada.com/h5wxPayNotify',
        signParams['trade_type'] = 'NATIVE';
    signParams['openid'] = "oA3_Av2rEKXp9sb_ElY8DRZ4FcTE";//微信商户平台证书
    signParams['product_id'] = '1234567890';
    signParams['pfx'] = null;//微信商户平台证书
    var wxpay = WXPay(signParams);
    wxpay.getBrandWCPayRequestParams(signParams, function (err, result) {
        if (err) {
            return response.error(err);
        } else {
            return response.success(result);
        }
    });
})

//小程序 付费加入部落  获取预支付id
AV.Cloud.define("weAppPrepayId", function (request, response) {
    var orderCode = request.params.orderCode;
    var openid = request.params.openid;
    if(!orderCode || !openid) {
        return response.error(common.getErrArr("错误的参数"));
    }
    var query = new AV.Query("Tribe_order");
    query.equalTo("orderCode", orderCode);
    query.first().then(function (order) {
        if (order) {
            var signParams = {};
            signParams['partner_key'] = apis['wxConfig']['partner_key'];
            signParams["appid"] = "wx2515506ab2f5b937";  //小程序 appid
            signParams['mch_id'] = "1269577001";
            signParams['nonce_str'] = randomString(32);
            signParams['body'] = '部落收费';
            signParams['out_trade_no'] = orderCode;
            signParams['total_fee'] = order.get("cost")*100;
            signParams['spbill_create_ip'] = '127.0.0.1';
            signParams['notify_url'] = 'http://tribe.aladada.com/weAppPayNotify',
                signParams['trade_type'] = 'JSAPI';
            signParams['openid'] = openid;
            var wxpay = WXPay(signParams);
            var sign = wxpay.sign(signParams);
            signParams.sign = sign;
            wxpay.createUnifiedOrder(signParams, function (err, result) {
                if (err) {
                    return response.error(err);
                } else {
                    var obj = {};
                    obj.appId = "wx2515506ab2f5b937";
                    obj.timeStamp = parseInt(new Date().getTime()/1000).toString();
                    obj.nonceStr = result.nonce_str;
                    obj.package = "prepay_id="+result.prepay_id;
                    obj.signType = "MD5";
                    obj.partner_key = apis['wxConfig']['partner_key'];
                    obj.paySign = wxpay.sign(obj);
                    return response.success(obj);
                }
            });
        } else {
            return response.error(common.getErrArr("无此订单"));
        }
    }, function (error) {
        return response.error(common.getErrArr(error))
    })
})

function randomString(len) {
    len = len || 32;
    var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
    /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
    var maxPos = $chars.length;
    var pwd = '';
    for (var i = 0; i < len; i++) {
        pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
    }
    return pwd;
}
